#!/usr/bin/python2
#-*- coding:utf8 -*-
# By sanyle 2018-05-03

import requests,sys,os,time
from bs4 import BeautifulSoup
import json
import urllib

reload(sys)
sys.setdefaultencoding('utf8')

def getvalues(item):
    values = []
    list = item.select("a")
    for i in range(len(list)):
        values.append(list[i].text)
    return values

def downloadImage(url):
    path = '/usr/syno/synoman/jp/covers/'
    pre_url = 'http://www.jp.com:5000/jp/covers/'

    image_name = url.split('/')[-1]
    command = 'curl ' + url + ' -o ' + path + image_name

    os.system(command)

    return pre_url + image_name

def getdata(vid):
    url = "https://javdb8.com/v/"+vid
    headers = {
            'Accept': '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
            'Connection': 'keep-alive',
            'host': 'javdb8.com',
            'Referer': 'https//javdb8.com/',
            'User-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW 64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36 QIHU 360SE'
            }
    proxies = {
            'http': 'http://127.0.0.1:3080',
            'https': 'http://127.0.0.1:3080'
            }
    r = requests.get(url, headers=headers, proxies=proxies)
    r = r.content.decode("utf-8")
    soup = BeautifulSoup(r,'lxml')
    list = soup.select(".panel-block")
    rt = {}
    rt["id"] = vid
    for i in range(len(list)-1):
        if len(list[i].select("strong")) == 0:
            break
        title=list[i].select("strong")[0].text
        if title == '類別:'.decode("utf-8"):
            rt["genres"] = getvalues(list[i])
        elif title == '日期:'.decode("utf-8"):
            rt["release_date"] = list[i].select('.value')[0].text
        elif title == '導演:'.decode("utf-8"):
            rt["directors"] = getvalues(list[i])
        elif title == '演員:'.decode("utf-8"):
            rt["actors"] = getvalues(list[i])
        elif title == '發行:'.decode("utf-8"):
            rt["writers"] = getvalues(list[i])
    
    rt["summary"]=soup.select("title")[0].text
    rt['backdrop'] = soup.select('.video-cover')[0].get("src")
    if rt['backdrop'].find("http")==-1:
            rt['backdrop']="https:"+rt['backdrop']
    rt['backdrop'] = downloadImage(rt['backdrop'])

    data = json.dumps(rt, ensure_ascii=False)
    return data

def main(argv):

    vid = argv[0]
    data = getdata(vid)
    print (data)

if __name__ == '__main__':
    main(sys.argv[1:])
